//添加时动态加载树
var settingAdd = {
			check: {
				enable: true,
				chkboxType: {"Y":"ps", "N":"ps"}
			},
			view: {
				dblClickExpand: false
			},
			data: {
				simpleData: {
					enable: true,
					idKey: "menuCode",
					pIdKey: "menuParentId",
				},
				key:{
					name:"menuName"
				}
			},
			
			callback: {
				beforeClick: beforeClickAdd,
				onCheck: onCheckAdd
			}
	};
	
	
	function beforeClickAdd(treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		zTree.checkNode(treeNode, !treeNode.checked, null, true);
		return false;
	}
	
	function onCheckAdd(e, treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
		nodes = zTree.getCheckedNodes(true),
		v = "";
		idv="";
		for (var i=0, l=nodes.length; i<l; i++) {
			v += nodes[i].menuName + ",";
			idv += nodes[i].menuCode + ",";
		}
		if (v.length > 0 ) v = v.substring(0, v.length-1);
		if (idv.length > 0 ) idv = idv.substring(0, idv.length-1);
		var menuObj = $("#menuSel");
		var idObj = $("#menuId");
		menuObj.attr("value", v);
		idObj.attr("value",idv);
	}
	
	function showMenuAdd() {
		var menuObj = $("#menuSel");
		var cityOffset = $("#menuSel").offset();
		$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + menuObj.outerHeight() + "px"}).slideDown("fast");
		
		$("body").bind("mousedown", onBodyDownAdd);
		var menuContent = $("#menuContent");
		menuContent[0].style.display="block";
	}
	function hideMenuAdd() {
		$("#menuContent").fadeOut("fast");
		$("body").unbind("mousedown", onBodyDownAdd);
	}
	function onBodyDownAdd(event) {
		if (!(event.target.id == "menuBtn" || event.target.id == "menuSel" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
			hideMenuAdd();
		}
	}
$("#menuSel").click(function(){
	showMenuAdd();
});
//修改时动态加载树
var settingUpdate = {
			check: {
				enable: true,
				chkboxType: {"Y":"ps", "N":"ps"}
			},
			view: {
				dblClickExpand: false
			},
			data: {
				simpleData: {
					enable: true,
					idKey: "menuCode",
					pIdKey: "menuParentId",
				},
				key:{
					name:"menuName"
				}
			},
			
			callback: {
				beforeClick: beforeClickUpdate,
				onCheck: onCheckUpdate
			}
	};
	
	
	function beforeClickUpdate(treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("updatetreeDemo");
		zTree.checkNode(treeNode, !treeNode.checked, null, true);
		return false;
	}
	
	function onCheckUpdate(e, treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("updatetreeDemo"),
		nodes = zTree.getCheckedNodes(true),
		v = "";
		idv="";
		for (var i=0, l=nodes.length; i<l; i++) {
			v += nodes[i].menuName + ",";
			idv += nodes[i].menuCode + ",";
		}
		if (v.length > 0 ) v = v.substring(0, v.length-1);
		if (idv.length > 0 ) idv = idv.substring(0, idv.length-1);
		var menuObj = $("#updatemenuSel");
		var idObj = $("#updatemenuId");
		menuObj.attr("value", v);
		idObj.attr("value",idv);
	}
	
	function showMenuUpdate() {
		var menuObj = $("#updatemenuSel");
		var cityOffset = $("#updatemenuSel").offset();
		$("#updatemenuContent").css({left:cityOffset.left + "px", top:cityOffset.top + menuObj.outerHeight() + "px"}).slideDown("fast");
		
		$("body").bind("mousedown", onBodyDownUpdate);
		var menuContent = $("#updatemenuContent");
		menuContent[0].style.display="block";
	}
	function hideMenuUpdate() {
		$("#updatemenuContent").fadeOut("fast");
		$("body").unbind("mousedown", onBodyDownUpdate);
	}
	function onBodyDownUpdate(event) {
		if (!(event.target.id == "menuBtn" || event.target.id == "updatemenuSel" || event.target.id == "updatemenuContent" || $(event.target).parents("#updatemenuContent").length>0)) {
			hideMenuUpdate();
		}
	}
$("#updatemenuSel").click(function(){
	showMenuUpdate();
});
//详情动态加载树
var settingDetail = {
			check: {
				enable: true,
				chkboxType: {"Y":"ps", "N":"ps"}
			},
			view: {
				dblClickExpand: false
			},
			data: {
				simpleData: {
					enable: true,
					idKey: "menuCode",
					pIdKey: "menuParentId",
				},
				key:{
					name:"menuName"
				}
				
			},
			callback: {
				beforeCheck: beforeCheck
			}
			
	};
function beforeCheck(treeId, treeNode) {
	return (treeNode.doCheck !== false);
}
	function showMenuDetail() {
		var menuObj = $("#detailmenuSel");
		var cityOffset = $("#detailmenuSel").offset();
		$("#detailmenuContent").css({left:cityOffset.left + "px", top:cityOffset.top + menuObj.outerHeight() + "px"}).slideDown("fast");
		
		$("body").bind("mousedown", onBodyDownDetail);
		var menuContent = $("#detailmenuContent");
		menuContent[0].style.display="block";
	}
	function hideMenuDetail() {
		$("#detailmenuContent").fadeOut("fast");
		$("body").unbind("mousedown", onBodyDownDetail);
	}
	function onBodyDownDetail(event) {
		if (!(event.target.id == "menuBtn" || event.target.id == "detailmenuSel" || event.target.id == "detailmenuContent" || $(event.target).parents("#detailmenuContent").length>0)) {
			hideMenuDetail();
		}
	}
$("#detailmenuSel").click(function(){
	showMenuDetail();
});
$(document).ready(function(){
	var currentPage = 1;
	var pageSize = 10;
	var token = $.zui.store.get("token");
	var userId = $.zui.store.get("userId");
	
	var queryListFun = function(){
		//获取列表数据
		var queryListUrl = adminQueryUrl + roleService + queryPageListMethod;
		
		var param = "action=queryRole";
		//搜索参数
		if ($("#queryRoleNameLike").val()!=''){
			param += "&RoleNameLike="+$("#queryRoleNameLike").val();
		}
		if (currentPage>0){
			param += "&currentPage="+(currentPage-1);
		}
		param += "&pageSize="+pageSize;
		param += "&currentPage="+(currentPage-1);
		
		console.log('queryListUrl='+queryListUrl);
		console.log('token='+token+",userId="+userId);
		console.log('param='+param);
		$.ajax({
			url:queryListUrl,
			type:'post',
			beforeSend:function(xhr){
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{"token":token,"userId":userId},
			data:param,
			dataType:"JSON",
			success:function(result){
				console.log(result.success);
				console.log(result.pageList);
				if (result.success== '1'){
					
					$('#listDataGrid').empty();
					$('#listDataGrid').data('zui.datagrid',null);
					$('#listPager').empty();
					$('#listPager').data('zui.pager',null);
					
					$('#listDataGrid').datagrid({
						checkable: true,
					    checkByClickRow: true,
					    selectable: true,
					    dataSource: {
					        cols:[
					            {name: 'Role_ID', label: '角色编号', width: 132},
					            {name: 'RoleName', label: '角色名称', width: 134},
					            {name: 'Opr_id', label: '操作员', width: 109},
					            {name: 'Opr_Date', label: '操作时间', width: 109},
					            {name: 'Remark', label: '角色描述', width: 287}
					        ],
					        cache:false,
					        array:result.pageList
					    }
					 
					});	
					
					// 手动进行初始化
					$('#listPager').pager({
					    page: currentPage,
					    recPerPage:pageSize,
					    elements:['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text','size_menu','goto'],
					    pageSizeOptions:[5,10,20,30,50,100],
					    recTotal: result.pageTotal
					});
				}
				else {
					new $.zui.Messager(result.msg, {
					    type: 'warning', // 定义颜色主题
					    placement: 'center' // 定义显示位置
					}).show();
				}
			},
			error:function(result){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning', // 定义颜色主题
				    placement: 'center' // 定义显示位置
				}).show();
			}
		});
	};
	//调起查询数据
	queryListFun();
	//查询
	$("#searchBtn").click(function(){
		queryListFun();
	});
	//监听分页，修改当前页，条数
	$('#listPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		pageSize = state.recPerPage;
		queryListFun();
	});
	
	
	//初始化添加
	$("#addBtn").click(function(){
		//获取角色权限列表
		var url = adminQueryUrl + roleService +RoleMenu ;
		var param = '';//请求到列表页面
		$("#addForm")[0].reset();
		console.log(url+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log(data.menuList)
				if (data.success=='1'){
					$.fn.zTree.init($("#treeDemo"), settingAdd,data.menuList);
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});

		
	});
	

	
	$("#addSaveBtn").click(function(){
			var validRoleNameUrl = adminQueryUrl + roleService + validRole ;
			console.log($("#menuId").val())
			$("#addForm").validate({
				rules:{
					addRoleName:{
						"required":true,
						"remote":{
							url:validRoleNameUrl,
							type:'post',
							beforeSend:function(xhr){//设置请求头信息
								xhr.setRequestHeader("token",token);
								xhr.setRequestHeader("userId",userId);
							},
							header:{'token':token,'userId':userId},
							dataType:'json',
							data:{
								'addRoleName':function(){
									return $("#addRoleName").val();
								}
							}
						}
					},
					menuSel:{
						"required":true,
						"minlength":2
					}
					
				},
				messages:{
					addRoleName:{
						"required":"请输入角色名称！",
						"remote":"该角色名称已经存在"
					},
					menuSel:{
						"required":"请选择角色权限！",
						"minlength":"请选择角色权限！"
					} 
				},
				submitHandler:function(form){
					console.log("xx:"+adminQueryUrl +  roleService + addMethod);
					
					$.ajax({
						url:adminQueryUrl + roleService + addMethod ,
						type:'post',
						dataType:'JSON',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						data:$(form).serialize(),
						success:function(data){
							console.log('data='+data);
							if (data.success == '1') {
			                	new $.zui.Messager('添加成功!', {
			    				    type: 'success',
			    				    placement:'center'
			    				}).show();
			                	queryListFun();
			                	$('#addModal').modal('hide', 'fit');
			                }
			                else{
			                	new $.zui.Messager(data.msg, {
			    				    type: 'warning',
			    				    placement:'center'
			    				}).show();
			                }
						},
						error:function(e){
							new $.zui.Messager('系统繁忙,请稍候再试!', {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
						}
					});
				}
			});	
	    });
	
	$("#updateBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#updateForm")[0].reset();
			var url = adminQueryUrl + roleService +initUpdate;
			var param = 'roleId='+selectedItems[0].Role_ID;//请求到列表页面
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$("#updateRoleName").val(data.roleMap.RoleName);
						$("#updateRemark").val(data.roleMap.Remark);
						$.fn.zTree.init($("#updatetreeDemo"), settingUpdate,data.menuList);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	//修改保存
	$("#updateSaveBtn").click(function(){
		var excludeRoleId = $('#listDataGrid').data('zui.datagrid').getCheckItems()[0].Role_ID;
		console.log("修改保存的ID"+excludeRoleId);
		var validRoleNameUrl = adminQueryUrl + roleService + validRole;
		$("#updateForm").validate({
			rules:{
				updateRoleName:{
					"required":true,
					"remote":{
						url:validRoleNameUrl,
						type:'post',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						dataType:'json',
						data:{
							'updateRoleName':function(){
								return $("#updateRoleName").val();
							},
							'excludeRoleId':function(){
								return excludeRoleId;
							}
						}
					}
				},
				updatemenuSel:{
					"required":true,
					"minlength":2
				}
				
			},
			messages:{
				updateRoleName:{
					"required":"请输入角色名称！",
					"remote":"该角色名称已经存在"
				},
				updatemenuSel:{
					"required":"请选择角色权限！",
					"minlength":"请选择角色权限！"
				}
			},
			submitHandler:function(form){
				var saveUrl = adminQueryUrl + roleService + updateMethod;
				$.ajax({
					url:saveUrl,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",userId);
					},
					header:{'token':token,'userId':userId},
					data:$(form).serialize()+"&excludeRoleId="+excludeRoleId,
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('修改成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	queryListFun();
		                	$('#updateModal').modal('hide', 'fit');
		                	queryListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	//显示删除确认框
	$("#deleteBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#deleteModal').modal('show', 'fit');
		}
	});
	//删除菜单
	$("#deleteRoleBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		var url = adminQueryUrl + roleService + deleteMethod;
		var param = 'role_id='+selectedItems[0].Role_ID;//请求到列表页面
		console.log('url='+url);
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				$('#deleteModal').modal('hide', 'fit');
				if (data.success=='1'){
	                	new $.zui.Messager('删除成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryListFun();
				}
                else{
                	new $.zui.Messager(data.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	//初始化详情
	$("#detailBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#detailForm")[0].reset();
			var url = adminQueryUrl + roleService + detailMethod;
			var param = 'roleId='+selectedItems[0].Role_ID;//请求到列表页面
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				header:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#detailModal').modal('show', 'fit');
						
						$("#detailRoleName").val(data.roleMap.RoleName);
						$("#detailRemark").val(data.roleMap.Remark);
						$.fn.zTree.init($("#detailtreeDemo"), settingDetail,data.detailList);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
});